package com.guguskins.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guguskins.back.common.constant.InventoryConstant;
import com.guguskins.back.common.constant.PrizeType;
import com.guguskins.back.common.constant.RecordConstant;
import com.guguskins.back.common.exception.GlobalMsgException;
import com.guguskins.back.entity.*;
import com.guguskins.back.entity.vo.MarketVo;
import com.guguskins.back.entity.vo.PageVo;
import com.guguskins.back.mapper.GuMarketMapper;
import com.guguskins.back.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mybatis-plus
 * @since 2021-07-02
 */
@Service
public class GuMarketServiceImpl extends ServiceImpl<GuMarketMapper, GuMarket> implements GuMarketService {

    @Autowired
    private GuMarketMapper marketMapper;


    @Autowired
    private GuBoxService boxService;

    @Autowired
    private GuGoodsService goodsService;

    @Autowired
    private GuPropService propService;

    @Autowired
    private GuDiscountService discountService;

    @Autowired
    private GuInventoryService inventoryService;

    @Autowired
    private GuRecordService recordService;

    @Autowired
    private GuPropNumService propNumService;

    @Override
    public PageVo<MarketVo> getPage(int p, int size, int type) {
        Page<GuMarket> marketPage = new Page<>(p, size);
        marketPage = this.page(marketPage, new LambdaQueryWrapper<GuMarket>() {
            {
                eq(type > 0, GuMarket::getMarketItemType, type);
                notIn(type == 4, GuMarket::getMarketItemType, 1, 2, 3);
            }
        });
        List<GuMarket> markets = marketPage.getRecords();
        List<MarketVo> marketVos = new ArrayList<>();
        markets.forEach(market -> {
            MarketVo marketVo = new MarketVo();
            BeanUtils.copyProperties(market, marketVo);
            switch (market.getMarketItemType()) {
                case PrizeType.BOX:
                    GuBox box = boxService.getBox(market.getMarketItemId());
                    marketVo.setItemImage(box.getBoxImageUrl());
                    marketVo.setItemLevel(5);
                    marketVo.setItemSubImage(box.getGoodsList().stream().max(Comparator.comparing(GuGoods::getGoodsPrice)).orElse(new GuGoods()).getGoodsIconUrl());
                    marketVo.setItemPrice(box.getBoxPrice());
                    marketVo.setItemName(box.getBoxName());
                    break;
                case PrizeType.GOODS:
                    GuGoods goods = goodsService.getById(market.getMarketItemId());
                    marketVo.setItemImage(goods.getGoodsIconUrl());
                    marketVo.setItemLevel(goods.getGoodsLevel());
                    marketVo.setItemName(goods.getGoodsName());
                    marketVo.setItemPrice(goods.getGoodsPrice());
                    break;
                case PrizeType.PROP:
                    GuProp prop = propService.getById(market.getMarketItemId());
                    marketVo.setItemImage(prop.getPropImage());
                    marketVo.setItemName(prop.getPropName());
                    marketVo.setItemLevel(5);
                    break;
                default:
                    throw new GlobalMsgException("系统错误");
            }
            marketVos.add(marketVo);
        });

        return new PageVo<>(marketVos, marketPage.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MarketVo exchange(Long userId, long marketId) {
        MarketVo marketVo = new MarketVo();
        //查询market
        GuMarket market = this.getById(marketId);
//        BigDecimal marketPrice = market.getMarketPrice();

        //查询用户咕币
        GuPropNum propNum = propNumService.getByUserIdAndPropId(userId, market.getMarketPropType());
        if (propNum.getPropNum().compareTo(market.getMarketNumber()) < 0) {
            throw new GlobalMsgException("剩余鸡蛋数量不足，请开箱后再兑换");
        }
        //扣减咕币
        propNum.setPropNum(propNum.getPropNum() - market.getMarketNumber());
        if (propNum.updateById()) {
            switch (market.getMarketItemType()) {
                case PrizeType.BOX:
//                GuBox box = boxService.getBox(inviteNum.getInvitePrizeId());
                    //添加库存
                    GuInventory boxInventory = inventoryService.addInventory(userId, null, InventoryConstant.Type.BOX, InventoryConstant.Source.MARKET, marketId, market.getMarketItemId(), null);
                    recordService.addRecord(userId, RecordConstant.TYPE.GAIN, InventoryConstant.Source.MARKET, marketId, PrizeType.BOX, market.getMarketItemId(), "兑换集市奖励领取奖品", null);
                    marketVo.setItemLevel(5);
                    GuBox box = boxService.getBox(market.getMarketItemId());
                    marketVo.setItemImage(box.getBoxImageUrl());
                    marketVo.setItemSubImage(box.getGoodsList().stream().max(Comparator.comparing(GuGoods::getGoodsPrice)).orElse(new GuGoods()).getGoodsIconUrl());
                    marketVo.setItemName(box.getBoxName());
                    marketVo.setItemPrice(box.getBoxPrice());
                    break;
                case PrizeType.GOODS:
                    GuInventory goodsInventory = inventoryService.addInventory(userId, null, InventoryConstant.Type.GOODS, InventoryConstant.Source.MARKET, marketId, market.getMarketItemId(), null);
                    recordService.addRecord(userId, RecordConstant.TYPE.GAIN, InventoryConstant.Source.MARKET, marketId, PrizeType.GOODS, market.getMarketItemId(), "兑换集市奖励领取奖品", null);
                    GuGoods goods = goodsService.getById(market.getMarketItemId());
                    marketVo.setItemLevel(goods.getGoodsLevel());
                    marketVo.setItemPrice(goods.getGoodsPrice());
                    marketVo.setItemImage(goods.getGoodsIconUrl());
                    marketVo.setItemName(goods.getGoodsName());
                    break;
                case PrizeType.PROP:
                    propNumService.addPropNum(userId, market.getMarketItemId());
                    recordService.addRecord(userId, RecordConstant.TYPE.GAIN, InventoryConstant.Source.MARKET,  marketId, PrizeType.PROP, market.getMarketItemId(), "兑换集市奖励领取奖品", null);
                    GuProp prop = propService.getById(market.getMarketItemId());
                    marketVo.setItemImage(prop.getPropImage());
                    marketVo.setItemName(prop.getPropName());
                    break;
                default:
                    throw new GlobalMsgException("参数错误");
            }
        }
        return marketVo;
    }

    @Override
    public PageVo<MarketVo> backPage(int pageNum, int pageSize) {
        if (pageNum == 1) {
           pageNum=0;
        } else {
            pageNum = (pageNum - 1) * pageSize;
        }
        List<MarketVo> marketVos = marketMapper.findAllPage(pageNum, pageSize);
        System.out.println(marketVos);
        marketVos.forEach(marketVo -> {
            switch (marketVo.getMarketItemType()) {
                case PrizeType.BOX:
                    GuBox box = boxService.getBox(marketVo.getMarketItemId());
                    marketVo.setItemImage(box.getBoxImageUrl());
                    marketVo.setItemLevel(5);
                    marketVo.setItemPrice(box.getBoxPrice());
                    marketVo.setItemName(box.getBoxName());
                    break;
                case PrizeType.GOODS:
                    GuGoods goods = goodsService.getById(marketVo.getMarketItemId());
                    marketVo.setItemImage(goods.getGoodsIconUrl());
                    marketVo.setItemLevel(goods.getGoodsLevel());
                    marketVo.setItemName(goods.getGoodsName());
                    marketVo.setItemPrice(goods.getGoodsPrice());
                    break;
                case PrizeType.PROP:
                    GuProp prop = propService.getById(marketVo.getMarketItemId());
                    marketVo.setItemImage(prop.getPropImage());
                    marketVo.setItemLevel(5);
                    break;
                case 4:
                    GuDiscount discount=discountService.getById(marketVo.getMarketId());
                    marketVo.setItemImage(discount.getDcImages());
                    marketVo.setItemName(discount.getDcTitle());
                    break;

                default:
                    throw new GlobalMsgException("系统错误");
            }

        });

        return new PageVo<>(marketVos, marketMapper.findAllCount());
    }

}
